require 'erb'

module Cucumber::Mingle::Formatters
  class ErbFormmatter
    BACKTRACE_FILTER_PATTERNS = [/vendor\/rails/, /vendor\/plugins\/cucumber/, /spec\/expectations/, /spec\/matchers/]
    
    def initialize(template, step_mother, options)
      input = File.read("#{File.dirname(__FILE__)}/#{template}.template")
      @template = ERB.new(input)
      @step_mother = step_mother
      @options = options
      
      @passed = {}
      @failed = {}
      @failed_steps = {}
      @not_automated = {}
      @autmated = {}
    end
    
    def visit_feature(feature)
      @feature = feature
    end
    
    def header_executing(header)
    end

    def scenario_executing(scenario)          
      @scenario_failed = false          
      @scenario_not_automated = false
      @failed_step = nil
    end

    def scenario_executed(scenario)
      category = (@scenario_not_automated ? @not_automated : @autmated) 
      category[@feature.card] ||= []
      category[@feature.card] << scenario
      unless @scenario_not_automated
        category = (@scenario_failed ? @failed : @passed)
        category[@feature.card] ||=[]
        category[@feature.card] << scenario
        @failed_steps[scenario] = @failed_step if @failed_step
      end
    end

    def step_passed(step, regexp, args)
    end

    def step_failed(step, regexp, args)
      @scenario_failed = true
      @failed_step = step      
    end

    def step_skipped(step, regexp, args)
    end

    def step_pending(step, regexp, args)
      @scenario_not_automated = true
    end
    
    def dump      
      test_report = Cucumber::Mingle::Card.new 
      test_report.name = "test report on #{Time.now}"
      test_report.description = @template.result(binding)
      test_report.save
    end
    
    def count_scenario(scenarios) 
      scenarios.inject(0) {|r, k| r+=k.last.length}
    end
    
    def source_comment(step)
      _, _, proc = step.regexp_args_proc(@step_mother)      
      proc.to_comment_line
    end
  end
end